package com.tdam2014.grupo3.flickr.interfaces;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.tdam2014.grupo3.entities.PhotoSet;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.Parameter;
import com.tdam2014.grupo3.flickr.Response;
import com.tdam2014.grupo3.flickr.Transport;

/**
 * Interface for working with Flickr PhotoSets.
 * 
 * @author Anthony Eden, adapted by Lucas Cunibertti for Flickr Viewer.
 */
public class PhotoSetInterface {

	public static final String METHOD_GET_LIST = "flickr.photosets.getList";

	private String apiKey;
	private Transport transportAPI;

	public PhotoSetInterface(String apiKey, Transport transportAPI) {
		this.apiKey = apiKey;
		this.transportAPI = transportAPI;
	}

	/**
	 * Get a list of all photosets for the specified user.
	 * This method does not require authentication.
	 * 
	 * @param peopleNsid The User id.
	 * @return The PhotoSets collection.
	 * @throws IOException
	 * @throws FlickrException
	 * @throws JSONException
	 */
	public ArrayList<PhotoSet> getList(String peopleNsid)
			throws IOException, FlickrException, JSONException {
		List<Parameter> parameters = new ArrayList<Parameter>();
		parameters.add(new Parameter("method", METHOD_GET_LIST));
		parameters.add(new Parameter("api_key", apiKey));
		parameters.add(new Parameter("user_id", peopleNsid));

		Response response = transportAPI.get(transportAPI.getPath(), parameters);
		
		if (response.isError()) {
			throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
		}
		
		JSONObject photoSetsObject = response.getData().getJSONObject("photosets");
		JSONArray photoSetArray = photoSetsObject.optJSONArray("photoset");
		ArrayList<PhotoSet> photoSets = new ArrayList<PhotoSet>();
		
		for (int i = 0; photoSetArray != null && i < photoSetArray.length(); i++) {
			JSONObject photoSetObject = photoSetArray.getJSONObject(i);
			photoSets.add(new PhotoSet(photoSetObject));
		}
		
		return photoSets;
	}
}